package org.openfans.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.openfans.domain.Facade;
import org.openfans.domain.Fans;
import org.openfans.util.ThreadFans;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

public class FansFormController extends SimpleFormController {
	private Facade facade = null;

	public void setFacade(Facade facade) {
		this.facade = facade;
	}

	public FansFormController() {
		setCommandName("fans");
		setCommandClass(Fans.class);
	}

	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		Fans fans = (Fans) command;
		if ("".equals(fans.getIcon())) {
			fans.setIcon("images/defaultFans.gif");
		}
		String name = request.getParameter("name");
		// 如果name不为null，表示还没有设置固定链接
		if (name != null) {
			name = name.trim();
			// 如果name栏不为空，就表示用户同意用它做自己的permenent link
			if (!"".equals(name)) {
				fans.setName(name);
				fans.setStatus(Fans.STATUS_PERMENENT);
			} else {
				// 现在暂时用id填充name
				fans.setName(String.valueOf(fans.getFansId()));
			}

		}

		facade.save(fans);

		return new ModelAndView(getSuccessView());
	}

	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		ThreadFans.authorize();
		return facade.getFans(ThreadFans.get().getFansId());
	}

}
